#include <ctime>
#include <iostream>

using std::cout;
using std::endl;

class Base
{
public:
    Base(long base = 0)
    : _base(base)
    {
        cout << "Base(long = 0)" << endl;
    }

    void print() const
    {
        cout << "Base::_base = " << _base << endl;
    }

    ~Base()
    {
        cout << "~Base()" << endl;
    }
private:
    long _base;
};

class Derived
: public Base
{
public:
    Derived(long base = 0, long derived = 0)
    : Base(base)
    , _derived(derived)
    {
        cout << "Derived(long = 0, long  = 0)" << endl;
    }

    void show() const
    {
        print();
        cout << "Derived::_derived = " << _derived << endl;
    }

    ~Derived()
    {
        cout << "~Derived()" << endl;
    }
private:
    long _derived;
};

void test()
{
    Base base(10);//基类对象
    base.print();

    cout << endl;
    Derived derived(11, 22);
    derived.show();

    cout << endl << "从派生类向基类进行转换" << endl;
    /* base = derived;//ok,1、可以将派生类对象赋值给基类对象 */
    //Base &operator=(const Base &rhs)
    //const Base &rhs = derived;
    base.operator=(derived);
    base.print();

    cout << endl;
    Base &ref = derived;//ok,2、可以将基类的引用绑定到派生类对象
    ref.print();

    cout << endl;
    Base *pbase = &derived;//ok,3、可以将基类的指针指向派生类对象
    pbase->print();
}

void test2()
{
    cout << "sizeof(Base) = " << sizeof(Base) << endl;
    cout << "sizeof(Derived) = " << sizeof(Derived) << endl;

    cout << endl;
    Base base(10);//基类对象
    base.print();

    cout << endl;
    Derived derived(11, 22);
    derived.show();

    cout << endl << "从基类向派生类进行转化" << endl;
    /* derived = base;//error,1、不能从基类对象赋值给派生类对象 */
    //Derived &operator=(const Derived &rhs)
    //const Derived &rhs = base
    /* derived.operator=(base); */

    cout << endl;
    //2、派生类的引用是不能绑定基类对象
    /* Derived &rhs = base;//error, */

    //3、派生类的指针是不能指向基类对象
    /* Derived *pderived = &base;//error */
    //原因

    //原本这种写法是不支持的，但是C++中有强制转换,破坏了这个
    //规则
    Derived *pderived = static_cast<Derived *>(&base);//不安全的

    Base *pbase = &derived;
    Derived *pderived2 = static_cast<Derived *>(pbase);//安全的

}
int main(int argc, char *argv[])
{
    test2();
    return 0;
}

